package com.gingko.duominuo.ui.fragment

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.gingko.duominuo.data.model.InjectAndInterceptVo
import com.gingko.duominuo.databinding.FragmentX5KernelBinding
import com.gingko.duominuo.utils.logi
import com.gingko.duominuo.utils.toast
import com.gingko.duominuo.viewmodel.BaseViewModel
import com.tencent.smtt.export.external.interfaces.JsPromptResult
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking


class X5KernelFragment : BaseWebViewFragment() {
    private var url: String? = null
    private var _binding: FragmentX5KernelBinding? = null


    private lateinit var mWebView: WebView

    private var isLoadFinish = false

    private var isShowToUser = false

    private var injectAndInterceptVo: InjectAndInterceptVo? = null

    companion object {
        private const val ARG_URL = "url"
        private const val ARG_INJECT_INTERCEPT = "injectAndIntercept"

        @JvmStatic
        fun newInstance(url: String, injectAndInterceptVo: InjectAndInterceptVo? = null) =
            X5KernelFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_URL, url)
                    putParcelable(ARG_INJECT_INTERCEPT, injectAndInterceptVo)
                }
            }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        url = arguments?.getString(ARG_URL)
        injectAndInterceptVo = arguments?.getParcelable(ARG_INJECT_INTERCEPT)
//        url = "https://club.m.autohome.com.cn/bbs/thread/fa6feaf2a90afa40/94867272-1.html"
    }

    override fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View? {
        _binding = FragmentX5KernelBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun getViewModel(): BaseViewModel? {
        return null
    }


    private fun loadAutoPlayJs() {
        injectAndInterceptVo?.js?.let {
            runBlocking {
                delay(300)
                mWebView.loadUrl(it)
            }
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        mWebView = WebView(requireContext())
        mWebView.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        initWebViewConfig()
        _binding?.flContainer?.addView(mWebView)
        if (url.isNullOrEmpty()) {
            "审核内容地址无效".toast()
        } else {
            mWebView.loadUrl(url)
        }
    }

    private fun initWebViewConfig() {
        mWebView.settings.run {
            cacheMode = WebSettings.LOAD_NO_CACHE
            domStorageEnabled = true
            databaseEnabled = true
            setAppCacheEnabled(true)
            useWideViewPort = true
            loadWithOverviewMode = true
            allowFileAccess = true
            setSupportZoom(false)
            builtInZoomControls = false
            javaScriptEnabled = true
            pluginState = WebSettings.PluginState.ON
            allowFileAccess = true
            setAllowFileAccessFromFileURLs(true)
            setAllowUniversalAccessFromFileURLs(true)
            loadWithOverviewMode = true
        }
        with(mWebView) {
            overScrollMode = View.OVER_SCROLL_NEVER
            webViewClient = object : WebViewClient() {

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    url?.logi("-------------->url")
                    if (injectAndInterceptVo?.pattern?.any { url?.contains(it) == true } == true) {
                        return true
                    }

                    val isHttpLink = url?.startsWith("http") == true
                    val isHttpsLink = url?.startsWith("https") == true
                    val isFileLink = url?.startsWith("file") == true
                    return if (!isHttpLink && !isHttpsLink && !isFileLink) {
                        try {
                            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                            true
                        } catch (e: Exception) {
                            // 如果找不到合适的APP来加载URL，则会抛出异常
                            e.printStackTrace()
                            false
                        }
                    } else {
                        false
                    }

                }

                override fun onPageStarted(p0: WebView?, p1: String?, p2: Bitmap?) {
                    super.onPageStarted(p0, p1, p2)
                    _binding?.pbLoading?.isVisible = true
                }

                override fun onPageFinished(p0: WebView?, p1: String?) {
                    super.onPageFinished(p0, p1)
                    "onPageFinished".logi("-----------》")
                    _binding?.pbLoading?.isVisible = false
                    _binding?.pbLoading?.progress = 0
                    isLoadFinish = true
                    if (isShowToUser) {
                        loadAutoPlayJs()
                    }
                }
            }
            webChromeClient = object : WebChromeClient() {
                override fun onJsAlert(
                    webview: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    //可以弹框或进行其它处理，但一定要回调result.confirm或者cancel
                    //这里要返回true否则内核会进行提示
                    return true
                }

                override fun onJsConfirm(
                    webview: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    //可以弹框或进行其它处理，但一定要回调result.confirm或者cancel
                    return true
                }

                override fun onJsBeforeUnload(
                    webview: WebView?,
                    url: String?,
                    message: String?,
                    result: JsResult?
                ): Boolean {
                    //可以弹框或进行其它处理，但一定要回调result.confirm或者cancel
                    return true
                }

                override fun onJsPrompt(
                    webview: WebView?,
                    url: String?,
                    message: String?,
                    defaultvalue: String?,
                    result: JsPromptResult?
                ): Boolean {
                    //可以弹框或进行其它处理，但一定要回调result.confirm或者cancel，confirm可以将用户输入作为参数
                    return true
                }

                override fun onProgressChanged(p0: WebView?, p1: Int) {
                    super.onProgressChanged(p0, p1)
                    if (p1 <= 100) {
                        _binding?.pbLoading?.progress = p1
                    }
                }
            }
            clearFocus()
        }
    }

    override fun autoPlayer() {
        if (isLoadFinish) {
            loadAutoPlayJs()
        }
    }

    override fun refresh() {
        isLoadFinish = false
        if (url.isNullOrEmpty()) {
            "审核内容地址无效".toast()
        } else {
            mWebView.loadUrl(url!!)
        }
    }

    override fun onResume() {
        super.onResume()
        mWebView.onResume()
        isShowToUser = true
        "onResume".logi("-----------》")
    }

    override fun canBack(): Boolean {
        return if (::mWebView.isInitialized && mWebView.canGoBack()) {
            mWebView.goBack()
            true
        } else {
            false
        }
    }

    override fun onPause() {
        super.onPause()
        isShowToUser = false
        mWebView.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding?.flContainer?.removeAllViews()
        _binding = null
        dismissLoading()
        mWebView.removeAllViews()
        mWebView.destroy()
        super.onDestroy()
    }
}